<?php defined('SYSPATH') or die('No direct script access.');
 
class Helpers
{
	public static function excerpt($inp,$limit)
	{
		//$rep = preg_replace("/<td class=\"photodesc\">(.*)<\/td>/", "", $inp);
		//$output = strip_tags($rep);
		mb_internal_encoding("UTF-8");
		$s = mb_substr($inp, 0, $limit);
		  return $s;
	}
	
	public static function login_bar()
	{
		# User / Login bar
		if(isset(Auth::instance()->get_user()->id))
		{
			$profil = ORM::factory('user',Auth::instance()->get_user()->id)->profiles;
			$login_bar = "U�ytkownik: ".$profil->imie . " " . $profil->nazwisko;
			if(Auth::instance()->logged_in('admin') != 0)
				$login_bar .= " | <a href=\"administracja\">Administracja</a>";
			$login_bar .= " | <a href=\"panel\">Panel u�ytkownika</a> | <a href=\"logout\">Wyloguj</a>";
			
		}else{
			$login_bar = '<a href="logowanie">Zaloguj si�</a> | <a href="rejestracja">Nowy u�ytkownik</a>';
		}
		return $login_bar;
	}
	
	public static function captcha()
	{
		//losowanie dw�ch liczb
		$vara = floor(rand(1,10));
		$varb = floor(rand(1,10));
		$summa = $vara + $varb;
		$cap_alert = $vara . " + " . $varb . " =";
		Session::instance()->set('spr_1275',$summa);
		$html = "<div class=\"captcha-box\">";
		$html .= "<span>$cap_alert</span>\n";
		$html .= "<input name=\"valid\" id=\"valid\" type=\"text\" style=\"width:40px;\" />\n";
		$html .= "<input type=\"hidden\" value=\"$summa\" name=\"captcha_hid\" id=\"captcha_hid\" />\n";
		$html .= "</div>";
		echo $html;
	}
	
	public static function mailer ($email,$title,$content)
	{
		require_once 'media/lib/swift/swift_required.php';
		$transport = Swift_SmtpTransport::newInstance(Kohana::config('appconf.email_smtp'), Kohana::config('appconf.email_port'))
		  ->setUsername(Kohana::config('appconf.email_username'))
		  ->setPassword(Kohana::config('appconf.email_password'));

		$mailer = Swift_Mailer::newInstance($transport);
		$message = Swift_Message::newInstance($title);
		$message->setFrom(array(Kohana::config('appconf.email_email') => Kohana::config('appconf.email_signature')));
		
		$message->setTo($email);
		$message->setBody(
			'<html>' .
			' <head></head>' .
			' <body>' .
				 $content .
			' </body>' .
			'</html>',
			  'text/html' //Mark the content-type as HTML
		);
		$result = $mailer->send($message);
	}
	
	// pierwszy cz�on url post�w
	public static function get_post_url($sup_id)
	{
		$page_model = new Model_Cms_Page;
		$url = $page_model->get_page_by_id($sup_id);
		return $url['url'];
	}
	
	public static function ucfirst($str) {
	   if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
            $string = mb_strtolower($string, $e);
            $upper = mb_strtoupper($string, $e);
            preg_match('#(.)#us', $upper, $matches);
            $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
        } else {
            $string = ucfirst($str);
        }
        return $string; 
	}
	
	public static function changepl_o($string)
	{
		$string = strtr($string, '���󥹌�����������', 'EeOoAaSsLlZzZzCcNn');
		$string = strtr($string, '������','ASZasz');
		$string = preg_replace("'[[:punct:][:space:]]'",'-',$string);
		$string = strtolower($string);
		$znaki = '-';
		$powtorzen = 1;
		$string = preg_replace_callback('#(['.$znaki.'])\1{'.$powtorzen.',}#', create_function('$a', 'return substr($a[0], 0,'.$powtorzen.');'), $string);
		return $string;
	}
	
	public static function valid_xhtml($string)
	{
		/* $in = preg_match_all('|<img(.*?)">|', $string, $dane);
		$html = '';
		foreach($dane[1] as $d)
		{
			$html .= $d."<br/>";
		}
		echo $html;exit; */
		$img = preg_replace('|<img(.*?)>|', '<img$1/>', $string);
		$from = array("<br>","<hr>");
		$to = array("<br/>","<hr/>");
		$out = str_replace($from,$to,$img);
		return $out;
	}
	
	public static function changepl($tekst)
	{
		$tabela = Array(
		//WIN
		"\xb9" => "a", "\xa5" => "A", "\xe6" => "c", "\xc6" => "C",
		"\xea" => "e", "\xca" => "E", "\xb3" => "l", "\xa3" => "L",
		"\xf3" => "o", "\xd3" => "O", "\x9c" => "s", "\x8c" => "S",
		"\x9f" => "z", "\xaf" => "Z", "\xbf" => "z", "\xac" => "Z",
		"\xf1" => "n", "\xd1" => "N",
		//UTF
		"\xc4\x85" => "a", "\xc4\x84" => "A", "\xc4\x87" => "c", "\xc4\x86" => "C",
		"\xc4\x99" => "e", "\xc4\x98" => "E", "\xc5\x82" => "l", "\xc5\x81" => "L",
		"\xc3\xb3" => "o", "\xc3\x93" => "O", "\xc5\x9b" => "s", "\xc5\x9a" => "S",
		"\xc5\xbc" => "z", "\xc5\xbb" => "Z", "\xc5\xba" => "z", "\xc5\xb9" => "Z",
		"\xc5\x84" => "n", "\xc5\x83" => "N",
		//ISO
		"\xb1" => "a", "\xa1" => "A", "\xe6" => "c", "\xc6" => "C",
		"\xea" => "e", "\xca" => "E", "\xb3" => "l", "\xa3" => "L",
		"\xf3" => "o", "\xd3" => "O", "\xb6" => "s", "\xa6" => "S",
		"\xbc" => "z", "\xac" => "Z", "\xbf" => "z", "\xaf" => "Z",
		"\xf1" => "n", "\xd1" => "N");

		$string =  strtr($tekst,$tabela);
		$string = preg_replace("'[[:punct:][:space:]]'",'_',$string);
		$string = strtolower($string);
		return $string;
	}
	
	public static function removeDir($directory)
	{ 
		// if the path has a slash at the end we remove it here
	if(substr($directory,-1) == '/')
	{
		$directory = substr($directory,0,-1);
	}

	// if the path is not valid or is not a directory ...
	if(!file_exists($directory) || !is_dir($directory))
	{
		// ... we return false and exit the function
		return FALSE;

	// ... if the path is not readable
	}elseif(!is_readable($directory))
	{
		// ... we return false and exit the function
		return FALSE;

	// ... else if the path is readable
	}else{

		// we open the directory
		$handle = opendir($directory);

		// and scan through the items inside
		while (FALSE !== ($item = readdir($handle)))
		{
			// if the filepointer is not the current directory
			// or the parent directory
			if($item != '.' && $item != '..')
			{
				// we build the new path to delete
				$path = $directory.'/'.$item;

				// if the new path is a directory
				if(is_dir($path)) 
				{
					// we call this function with the new path
					Helpers::removeDir($path);

				// if the new path is a file
				}else{
					// we remove the file
					unlink($path);
				}
			}
		}
		// close the directory
		closedir($handle);

		
			// try to delete the now empty directory
			if(!rmdir($directory))
			{
				// return false if not possible
				return FALSE;
			}
		
		// return success
		return TRUE;
	}
	}
	
	public static function getDirectoryList ($directory) 
	{
		$results = array();
		$handler = opendir($directory);
		$i=0;
		while ($file = readdir($handler)) {
		  if ($file != "." && $file != "..") {
			$file_ext = strtolower(substr($file, strrpos($file, '.') + 1));
			$results[$i]['file_name'] = $file;
			$results[$i]['file_ext'] = $file_ext;
			$part = explode(".",$file);
			$results[$i]['file_base'] = $part[0];
			$results[$i]['id'] = $i;
			$i++;
		  }
		}
		closedir($handler);
		return $results;
	}
	
	public static function rss_reader($limit)
	{		
		$url = "http://www.futbol.pl/rss/";
		$rss = simplexml_load_file($url);
		$rss_feeds = array();
		if($rss)
		{
			$rss_feeds['title'] = $rss->channel->title;
			//echo '<li>'.$rss->channel->pubDate.'</li>';
			$items = $rss->channel->item;
			
			$i=0;
			foreach($items as $item)
			{
				if($i < $limit)
				{
					$rss_feeds['items'][$i]['title'] = $item->title;
					$rss_feeds['items'][$i]['link'] = $item->link;
					$rss_feeds['items'][$i]['date'] = $item->pubDate;
					$rss_feeds['items'][$i]['description'] = $item->description;
					
				}
				$i++;
			}
		}
		return $rss_feeds;
	}

}
?>